#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <strings.h>
#include <functional>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "log.hpp"
#include"InetAddr.hpp"

using namespace LogModule;

using func_t = std::function<void(int sockfd,const std::string &,InetAddr peer)>;

const int defaultfd = -1;
class UdpServer
{
public:
    UdpServer(u_int16_t port, func_t func)
        : _sockfd(defaultfd),
          _port(port),
          _isrunning(false),
          _func(func)
    {
    }

    void Init()
    {
        //创建套接字
        _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(LogLevel::FATAL) << "socket error!";
            exit(1);
        }
        LOG(LogLevel::INFO) << "socket success,sockfd:" << _sockfd;
        //创建sockaddr_in对象
        struct sockaddr_in local;
        bzero(&local, sizeof(local));
        local.sin_family = AF_INET;
        //绑定socket信息
        local.sin_port = htons(_port);
        local.sin_addr.s_addr = INADDR_ANY;
        //显示bind绑定
        int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
        if (n < 0)
        {
            LOG(LogLevel::FATAL) << "bind error";
            exit(2);
        }
        LOG(LogLevel::INFO) << "bind success,sockdf:" << _sockfd;
    }

    void Start()
    {
        _isrunning = true;
        while (_isrunning)
        {
            char buffer[1024];
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            //收消息
            ssize_t s = recvfrom(_sockfd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&peer, &len);
           //std::cout << buffer << std::endl;
            if (s > 0)
            {
                
                buffer[s] = 0;
                //std::cout << buffer << std::endl;
                InetAddr client(peer);
                 _func(_sockfd,buffer,client);
                //sendto(_sockfd, result.c_str(), result.size(), 0, (struct sockaddr *)&peer, len);
            }
        }
    }

    ~UdpServer()
    {
    }

private:
    int _sockfd;
    uint16_t _port;
    bool _isrunning;
    func_t _func;
};